package com.flying.acls.domain.sid;

import com.flying.acls.domain.context.ContextStringValueResolver;
import com.flying.acls.domain.context.ExpressionContext;
import com.flying.acls.model.ExpressionType;
import com.flying.acls.model.Sid;
import com.flying.acls.model.SidType;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

public class PatternBasedSidBuilder {
    private SidPatternInfo sidPatternInfo;
    private ContextStringValueResolver stringResolver;

    public PatternBasedSidBuilder(ContextStringValueResolver stringResolver, SidPatternInfo sidPatternInfo) {
        this.stringResolver = stringResolver;
        this.sidPatternInfo = sidPatternInfo;
    }

    public List<Sid> build(ExpressionContext context, String username, List<String> roles) {
        List<String> expressions = stringResolver.resolveStringValue(context, sidPatternInfo.getPatterns());
        List<Sid> sids = new ArrayList<>(expressions.size() + roles.size() + 1);

        sids.add(SidFactory.get(SidType.USER, ExpressionType.DIRECT, username));

        for (String expression : expressions) {
            sids.add(SidFactory.get(SidType.USER, ExpressionType.DIRECT, expression));
        }

        for (String role : roles) {
            sids.add(SidFactory.get(SidType.USER, ExpressionType.DIRECT, role));
        }
        return sids;
    }
}